package com.site.wisdom_construction.Server;

import com.alibaba.fastjson.JSONObject;
import com.site.wisdom_construction.entity.userAuthorityModule.User;
import com.site.wisdom_construction.responseEntity.JsonResult;
import com.site.wisdom_construction.util.verification.NoToken;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import com.site.wisdom_construction.Server.WebSocketServer;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

/**
 * @Author daiyifei
 * @Date 2022/3/12
 * @Description
 */
@Api(tags = "数据类接口")
@RestController
@RequestMapping("testController")
@CrossOrigin
public class testController {

    WebSocketServer webSocketServer = new WebSocketServer();
    /** userAuthorityModule */
    @PostMapping(value = "/toUser")
    @NoToken
    public JsonResult toUser(@RequestParam("file") MultipartFile file) throws IOException {

        String oldFileName = file.getOriginalFilename();
        int lastDotIndex = oldFileName.lastIndexOf(".");
        String extName = oldFileName.substring(lastDotIndex);
        String newName = UUID.randomUUID() + extName;
        //   /root/img/    E:/test/
        File excelFile =
                new File("G:/test/"
                        + newName);
        try {
            file.transferTo(excelFile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] data = null;
        try (InputStream in = new FileInputStream("G:/test/"
                + newName)){
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回Base64编码过的字节数组字符串

        JsonResult jsonResult = new JsonResult();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cmd","upload person");
        jsonObject.put("id","340122199608100000");
        jsonObject.put("name","代逸飞");
        jsonObject.put("role",1);
        jsonObject.put("kind",0);
        jsonObject.put("term_start","2021/11/10 12:00:00");
        jsonObject.put("term","2032/12/18 16:45:30");
        jsonObject.put("reg_image",Base64.getEncoder().encodeToString(data));
       // webSocketServer.BroadCastInfo(jsonObject.toJSONString());

        System.out.println("成功了");
        return jsonResult;
    }

    public static void convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        //BASE64Encoder encoder = new BASE64Encoder();
        //String base64Str = encoder.encode(data);
        //return base64Str;
    }

    @PostMapping(value = "/imgBase64")
    @NoToken
    public String picture(@RequestParam("file") MultipartFile file) {
        String oldFileName = file.getOriginalFilename();
        int lastDotIndex = oldFileName.lastIndexOf(".");
        String extName = oldFileName.substring(lastDotIndex);
        String newName = UUID.randomUUID() + extName;
        //   /root/img/    E:/test/
        File excelFile =
                new File("G:/test/"
                        + newName);
        try {
            file.transferTo(excelFile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] data = null;
        try (InputStream in = new FileInputStream("G:/test/"
                + newName)){
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回Base64编码过的字节数组字符串
        System.out.println("本地图片转换Base64: ");
        System.out.println(Base64.getEncoder().encodeToString(data));
        return "false";
    }

    @PostMapping(value = "/getBase64")
    @NoToken
    public String getBase64(@RequestBody Map map) {
        String urlC = (String) map.get("urlC");
        InputStream in = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        //读取图片字节数组
        try {
            URL url = new URL(urlC);
            final byte[] by = new byte[1024];
            // 创建链接获取图片
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            in = conn.getInputStream();
            int len = -1;
            while ((len = in.read(by)) != -1) {
                data.write(by, 0, len);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        String encode = encoder.encode(data.toByteArray());
        encode = encode.replaceAll("[\\s*\t\n\r]", "");
        return "data:image/png;base64,"+encode;
    }
}
